package servlet;

import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import java.sql.ResultSet;
import java.util.HashMap;
import javax.servlet.ServletOutputStream;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperRunManager;
import session.stateless.EmployeeSessionBeanLocal;

@WebServlet(name = "Controller", urlPatterns = {"/Controller", "/Controller?*"})
public class Controller extends HttpServlet {

    @Resource(name = "merlionerp_db")
    private DataSource merlionerp_db;
    @EJB
    EmployeeSessionBeanLocal employeeSessionBeanLocal;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {


            String action = request.getParameter("action");
            if (action == null) {
                action = "index";
            }
            if (action.equals("index")) {
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
            if (action.equals("exportMyEventsToPDF")) {
                exportMyEventsToPDFBySQLConn(request, response);
            }


        } catch (Exception ex) {
            ex.printStackTrace();
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }

    private void exportMyEventsToPDFBySQLConn(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userId = request.getParameter("userId");
            System.out.println (userId);
//            String strSQL = "SELECT E.EVENTID, E.EVENTNAME, E.STARTDATETIME, E.ENDDATETIME, V.VENUENAME, V.VENUELOCATION, E.STATUS "
//                    + "FROM EVENT AS E INNER JOIN VENUE AS V ON E.VENUE_VENUEID = V.VENUEID "
//                    + "WHERE E.SYSTEMUSER_SYSTEMUSERID = " + request.getSession().getAttribute("systemUserId").toString();
//            
            String strSQL= "";
            ResultSet rsEvents = merlionerp_db.getConnection().prepareStatement(strSQL).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsEvents);
            InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("/Jasper_reports/EmployeeWelcome2.jasper");
            response.setContentType("application/pdf");
            ServletOutputStream outputStream = response.getOutputStream();
            HashMap parameters = new HashMap();
            parameters.put("IMAGEPATH", "http://localhost:8080/MerlionERP-war/Jasper_reports/merlionV1.jpg");
            parameters.put("employee_ID", userId);
            String pwd = employeeSessionBeanLocal.getPassword(userId);
            parameters.put("pw", pwd);
            JasperRunManager.runReportToPdfStream(reportStream, outputStream, parameters, jrResultSetDataSource);
            outputStream.flush();
            outputStream.close();

        } catch (JRException jrex) {
            System.out.println("********** Jasperreport Exception");
            jrex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}